﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Forms;
using Marmat.Foundation;

namespace Marmat.FrameWork
{
    /// <summary>
    /// 
    /// </summary>
    public static class WinHostExtension
    {
        /// <summary>
        /// 运行win应用程序并阻塞调用线程，直到程序关闭。
        /// </summary>
        /// <param name="host"></param>
        public static void Run(this IHost host)
        {
            if (host is null)
                throw new ArgumentNullException(nameof(host));
            var upgrade = SystemCommand.GetService<IUpgrade>();
            if (upgrade?.CheckUpgrade() == true)
            {
                upgrade.Upgrade();
                return;
            }
            var application = SystemCommand.GetService<IApplicationSupport>();
            if (application is not null)
            {
                Application.ThreadException += (sender, e) => application.ThreadException(sender, e.Exception);
                AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
                {
                    if (e.ExceptionObject is Exception exception)
                        application.ThreadException(sender, exception);
                };
            }
            Login();
        }

        /// <summary>
        /// 执行登录过程。
        /// </summary>
        internal static void Login()
        {
            ILoginForm login = SystemCommand.GetService<ILoginForm>();
            if (login.ShowDialog(out string userID))
            {
                var userProvider = SystemCommand.GetService<IUserProvider>();
                if (userProvider is not null)
                    userProvider.UserID = userID;
                ILoadUserSettingForm awaitForm = SystemCommand.GetService<ILoadUserSettingForm>();
                if (awaitForm! != null)
                {
                    awaitForm.Show();
                    Application.DoEvents();
                }
                IEnumerable<ILoadUserSetting> userSettings = SystemCommand.GetServices<ILoadUserSetting>();
                foreach (var userSetting in userSettings)
                {
                    userSetting.ExecuteCommand(userID);
                }
                IMainForm mainForm = SystemCommand.GetService<IMainForm>();
                awaitForm?.Close();

                mainForm.ShowDialog();

                foreach (var userSetting in userSettings)
                {
                    userSetting.Dispose();
                }
            }
        }
    }
}
